import { http, HttpResponse } from 'msw';

console.log('[MSW] handlers.js loaded');

// 模拟数据
let tasks = [
  { id: 1, name: '测试任务 1' },
  { id: 2, name: '测试任务 2' },
];
let cartItems = [];
let orders = [];
const tokenMap = new Map();
const dishes = [
  { dishId: 101, dishName: '宫保鸡丁', price: 25.0, categoryId: 1, isRecommended: true, isNew: true },
  { dishId: 102, dishName: '红烧肉', price: 32.0, categoryId: 1 },
  { dishId: 201, dishName: '可乐', price: 5.0, categoryId: 2 },
];
const reviews = [
  { reviewId: 201, userId: 'user1', rating: 5, comment: '很好吃', reply: '' },
  { reviewId: 202, userId: 'user2', rating: 4, comment: '不错', reply: '' },
];
const categories = [
  { categoryId: 1, categoryName: '主菜' },
  { categoryId: 2, categoryName: '饮品' },
  { categoryId: 3, categoryName: '甜点' },
];

// 用户数据
const users = [
  {
    userId: '111',
    username: 'kwt',
    password: '111',
    phoneNumber: '12345678910',
    permissions: ['ADMIN', 'MANAGE_ORDERS'],
    role: 'ADMIN',
  },
  {
    userId: '222',
    username: 'kzh',
    password: '222',
    phoneNumber: '12345678911',
    permissions: ['USER'],
    role: 'USER',
  },
  {
    userId: '333',
    username: '3',
    password: '333',
    phoneNumber: '12345678912',
    permissions: ['MERCHANT'],
    role: 'MERCHANT',
  },
];

// 工具函数
function getUserFromToken(token) {
  const record = tokenMap.get(token);
  if (!record) return null;
  return users.find(u => u.userId === record.userId);
}

export const handlers = [

  // —— 登录相关 ——
  http.post('/api/v1/auth/login', async ({ request }) => {
    const { username, password } = await request.json();
    const user = users.find(u => u.username === username && u.password === password);
    if (!user) {
      return HttpResponse.json({ code: 2001, message: '用户名或密码错误' }, { status: 401 });
    }
    const token = crypto.randomUUID();
    tokenMap.set(token, { userId: user.userId, role: user.role });
    return HttpResponse.json({
      code: 0,
      data: {
        token,
        userId: user.userId,
        username: user.username,
        permissions: user.permissions,
      },
    });
  }),

  http.get('/api/v1/user', ({ request }) => {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '').trim();
    const user = getUserFromToken(token);
    if (!user) return HttpResponse.json({ code: 401, message: '无效Token' }, { status: 401 });
    return HttpResponse.json({
      code: 0,
      data: {
        userId: user.userId,
        username: user.username,
        permissions: user.permissions,
        role: user.role,
      },
    });
  }),

http.post('/api/v1/auth/register', async ({ request }) => {
  const requestBody = await request.json();
  console.log(requestBody);  // 查看请求体数据

  const { phoneNumber, password, role } = requestBody;

  if (!phoneNumber || !password || !role) {
    return HttpResponse.json({ code: 400, message: '手机号、密码和角色不能为空' }, { status: 400 });
  }

  // 根据角色设置权限
  let permissions = [];
  switch (role) {
    case 'MERCHANT':
      permissions = ['MERCHANT'];
      break;
    case 'USER':
      permissions = ['USER'];
      break;
    default:
      return HttpResponse.json({ code: 400, message: '无效角色' }, { status: 400 });
  }

  // 创建用户
  const newUser = {
    userId: Date.now().toString(),
    username: phoneNumber,  // 这里假设 username 是手机号
    password,
    phoneNumber,
    permissions,
    role,
  };

  users.push(newUser); // 将新用户加入到用户数据中

  return HttpResponse.json({ code: 0, message: '注册成功', data: { userId: newUser.userId, phoneNumber } }, { status: 201 });
}),


    http.post('/api/v1/auth/send-verification-code', async ({ request }) => {
  const { phoneNumber, type } = await request.json();

  // 模拟手机号校验
  if (!/^\d{11}$/.test(phoneNumber)) {
    return HttpResponse.json({ code: 400, message: '无效的手机号' }, { status: 400 });
  }

  // 这里模拟生成验证码并发送
  const verificationCode = Math.floor(100000 + Math.random() * 900000);  // 生成一个6位的验证码

  // 在控制台打印验证码，模拟发送验证码的过程
  console.log(`发送验证码：${verificationCode} 到手机号: ${phoneNumber}`);

  // 返回成功响应
  return HttpResponse.json({ code: 0, message: '验证码发送成功' });
}),

    // 新增重置密码接口
http.post('/api/v1/auth/reset-password', async ({ request }) => {
  const { email } = await request.json();
  // 模拟发送重置链接
  return HttpResponse.json({
    code: 0,
    message: '重置链接已发送至邮箱'
  });
}),
  // —— 菜单相关 ——
http.get('/api/v1/menu', ({ request }) => {
  const token = request.headers.get('Authorization')?.replace('Bearer ', '').trim()
  const user = getUserFromToken(token)
  if (!user) return HttpResponse.json({ code: 401, message: '无权限' }, { status: 401 })

  const baseMenu = [
    { id: 1, name: '首页', path: '/' },
    { id: 2, name: '任务管理', path: '/tasks' },
    { id: 3, name: '购物车', path: '/cart' },
  ]

  if (user.permissions.includes('ADMIN')) {
    baseMenu.push({ id: 99, name: '管理员', path: '/admin' })
  }

  return HttpResponse.json({ code: 0, data: baseMenu })
}),


  http.get('/api/v1/menu/categories', () =>
    HttpResponse.json({ code: 0, data: { categories, total: categories.length } })
  ),

  http.get('/api/v1/menu/dishes', ({ request }) => {
    const categoryId = parseInt(new URL(request.url).searchParams.get('categoryId'));
    const filtered = categoryId ? dishes.filter(d => d.categoryId === categoryId) : dishes;
    return HttpResponse.json({ code: 0, data: { dishes: filtered, total: filtered.length } });
  }),

  http.get('/api/v1/menu/dishes/:dishId', ({ params }) => {
    const dish = dishes.find(d => d.dishId === parseInt(params.dishId));
    if (!dish) return HttpResponse.json({ code: 6001, message: '菜品不存在' }, { status: 404 });
    return HttpResponse.json({ code: 0, data: dish });
  }),

  // —— 购物车 ——
  http.get('/api/v1/cart', () => HttpResponse.json({ code: 0, data: cartItems })),

  http.post('/api/v1/cart', async ({ request }) => {
    const { dishId, quantity } = await request.json();
    const dish = dishes.find(d => d.dishId === dishId);
    if (!dish || quantity <= 0) {
      return HttpResponse.json({ code: 400, message: '无效参数' }, { status: 400 });
    }
    const item = { id: Date.now(), name: dish.dishName, quantity, price: dish.price };
    cartItems.push(item);
    return HttpResponse.json({ code: 0, data: item });
  }),

  http.delete('/api/v1/cart/:id', ({ params }) => {
    const index = cartItems.findIndex(i => i.id == params.id);
    if (index === -1) return HttpResponse.json({ code: 404, message: '购物车项不存在' }, { status: 404 });
    cartItems.splice(index, 1);
    return HttpResponse.json({ code: 0 });
  }),

  http.post('/api/v1/cart/checkout', () => {
    const orderId = Date.now();
    const totalAmount = cartItems.reduce((sum, i) => sum + i.price * i.quantity, 0);
    orders.push({ orderId, items: [...cartItems], totalAmount, status: 'PENDING' });
    cartItems = [];
    return HttpResponse.json({ code: 0, data: { orderId, totalAmount } });
  }),

  // —— 支付、优惠券 ——
  http.get('/api/v1/coupons/available', () =>
    HttpResponse.json({ code: 0, data: { coupons: [{ couponId: 1, discountAmount: 5.0 }] } })
  ),

  http.post('/api/v1/payment/pay', async ({ request }) => {
    const { orderId } = await request.json();
    return HttpResponse.json({ code: 0, data: { paymentUrl: `https://fakepay.com/pay?orderId=${orderId}` } });
  }),

  // —— 管理员用户管理 ——
  http.get('/api/v1/admin/users', ({ request }) => {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '').trim();
    const user = getUserFromToken(token);
    if (!user || !user.permissions.includes('ADMIN')) {
      return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
    }
    return HttpResponse.json({
      code: 0,
      data: {
        users: users.map(u => ({
          userId: u.userId,
          username: u.username,
          phone: u.phone || '',
          permissions: u.permissions.join(','),
        })),
      },
    });
  }),

  http.post('/api/v1/admin/users/:userId', async ({ params, request }) => {
    const user = users.find(u => u.userId == params.userId);
    if (!user) return HttpResponse.json({ code: 404, message: '用户不存在' }, { status: 404 });
    const updates = await request.json();
    Object.assign(user, {
      username: updates.username || user.username,
      phone: updates.phone || user.phone,
      permissions: updates.permissions ? updates.permissions.split(',') : user.permissions,
    });
    return HttpResponse.json({ code: 0, message: '更新成功' });
  }),

  http.delete('/api/v1/admin/users/:userId', ({ params }) => {
    const index = users.findIndex(u => u.userId == params.userId);
    if (index === -1) return HttpResponse.json({ code: 404, message: '用户不存在' }, { status: 404 });
    users.splice(index, 1);
    return HttpResponse.json({ code: 0, message: '删除成功' });
  }),

  // —— 管理员菜品管理（4.5.4 - 4.5.6） ——
http.post('/api/v1/admin/dishes', async ({ request, headers }) => {
  const user = getUserFromToken(headers.get('Authorization')?.replace('Bearer ', '').trim());
  if (!user || !user.permissions.includes('MERCHANT')) {
    return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
  }

  const { name, price, category, stock, imageUrl, description } = await request.json();
  if (!categories.some(c => c.categoryId === category)) {
    return HttpResponse.json({ code: 10008, message: '分类不存在' }, { status: 400 });
  }
  if (stock < 0) {
    return HttpResponse.json({ code: 10009, message: '库存无效' }, { status: 400 });
  }

  const newDish = {
    dishId: Date.now(),
    dishName: name,
    price,
    categoryId: category,
    stock,
    imageUrl: imageUrl || '',
    description: description || '',
  };
  dishes.push(newDish);
  return HttpResponse.json({ code: 0, message: '添加成功', data: { dishId: newDish.dishId } });
}),

 http.post('/api/v1/admin/dishes/:dishId', async ({ params, request, headers }) => {
  const user = getUserFromToken(headers.get('Authorization')?.replace('Bearer ', '').trim());
  if (!user || !user.permissions.includes('MERCHANT')) {
    return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
  }

  const dish = dishes.find(d => d.dishId === parseInt(params.dishId));
  if (!dish) return HttpResponse.json({ code: 10010, message: '菜品不存在' }, { status: 404 });

  const updates = await request.json();
  if (updates.category && !categories.some(c => c.categoryId === updates.category)) {
    return HttpResponse.json({ code: 10008, message: '分类不存在' }, { status: 400 });
  }
  if (updates.stock !== undefined && updates.stock < 0) {
    return HttpResponse.json({ code: 10009, message: '库存无效' }, { status: 400 });
  }

  Object.assign(dish, {
    dishName: updates.name ?? dish.dishName,
    price: updates.price ?? dish.price,
    categoryId: updates.category ?? dish.categoryId,
    stock: updates.stock ?? dish.stock,
    imageUrl: updates.imageUrl ?? dish.imageUrl,
    description: updates.description ?? dish.description,
  });

  return HttpResponse.json({ code: 0, message: '更新成功', data: { dishId: dish.dishId } });
}),

http.delete('/api/v1/admin/dishes/:dishId', ({ params, request }) => {
  const authHeader = request.headers.get('Authorization') || request.headers.get('authorization');
  const token = authHeader?.replace('Bearer ', '').trim();

  const user = getUserFromToken(token);
  if (!user || !user.permissions.includes('MERCHANT')) {
    return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
  }

  const index = dishes.findIndex(d => d.dishId === parseInt(params.dishId));
  if (index === -1) return HttpResponse.json({ code: 10010, message: '菜品不存在' }, { status: 404 });
  dishes.splice(index, 1);
  return HttpResponse.json({ code: 0, message: '删除成功', data: null });
}),




  // —— 管理员订单管理（4.5.7 - 4.5.8） ——
  http.get('/api/v1/admin/orders', ({ request }) => {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '').trim();
    const user = getUserFromToken(token);
    if (!user || !user.permissions.includes('ADMIN')) {
      return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
    }

    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const status = url.searchParams.get('status');

    if (isNaN(page) || isNaN(pageSize)) {
      return HttpResponse.json({ code: 10011, message: '分页参数无效' }, { status: 400 });
    }

    let filtered = orders;
    if (status) filtered = filtered.filter(o => o.status === status);

    return HttpResponse.json({
      code: 0,
      message: '获取成功',
      data: { orders: filtered.slice((page - 1) * pageSize, page * pageSize) },
    });
  }),

  http.post('/api/v1/admin/orders/:orderId/cancel', ({ params, headers }) => {
    const user = getUserFromToken(headers.get('Authorization')?.replace('Bearer ', '').trim());
    if (!user || !user.permissions.includes('ADMIN')) {
      return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
    }

    const order = orders.find(o => o.orderId === parseInt(params.orderId));
    if (!order) return HttpResponse.json({ code: 10013, message: '订单不存在' }, { status: 404 });
    if (order.status !== 'PENDING') {
      return HttpResponse.json({ code: 10014, message: '订单状态不可取消' }, { status: 400 });
    }

    order.status = 'CANCELLED';
    return HttpResponse.json({ code: 0, message: '取消成功', data: { orderId: order.orderId } });
  }),

  // —— 管理员评价管理（4.5.9 - 4.5.10） ——
  http.get('/api/v1/admin/reviews', ({ request }) => {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '').trim();
    const user = getUserFromToken(token);
    if (!user || !user.permissions.includes('ADMIN')) {
      return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
    }

    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const userId = url.searchParams.get('userId');

    let filtered = reviews;
    if (userId) filtered = filtered.filter(r => r.userId === userId);

    return HttpResponse.json({
      code: 0,
      message: '获取成功',
      data: { reviews: filtered.slice((page - 1) * pageSize, page * pageSize) },
    });
  }),

  http.post('/api/v1/admin/reviews/:reviewId/reply', async ({ params, request, headers }) => {
    const user = getUserFromToken(headers.get('Authorization')?.replace('Bearer ', '').trim());
    if (!user || !user.permissions.includes('ADMIN')) {
      return HttpResponse.json({ code: 403, message: '无权限访问' }, { status: 403 });
    }

    const review = reviews.find(r => r.reviewId === parseInt(params.reviewId));
    if (!review) return HttpResponse.json({ code: 10015, message: '评价不存在' }, { status: 404 });

    const { reply } = await request.json();
    review.reply = reply;
    return HttpResponse.json({ code: 0, message: '回复成功', data: { reviewId: review.reviewId } });
  }),

];
